package com.wkh.datastructure;

import java.util.Iterator;
import java.util.function.Consumer;

// 动态数组
public class DynamicArray<E> implements Iterable<E>{
    private Integer size = 0; // 逻辑大小
    private Integer capacity = 8; // 数组初始容量
    private Object[] array = {}; // 初始数组

    //在数组末尾添加
    public void addLast(E element){
        /*array[size] = element;
        size++;*/
        add(size,element);
    }

    //在指定索引处添加元素或数组末尾添加
    public void add(Integer index ,E element){
        //扩容
        checkAndGrow();
        if (index >=0 && index < size){
            System.arraycopy(array,index,array,index+1,size-index);
        }
        array[index] = element;
        size++;
    }
    //扩容的逻辑
    private void checkAndGrow() {
        //懒加载
        if (size == 0){
            array = new Object[capacity];
        }
        if (size == capacity){
            capacity += capacity>>1;
            Object[] newArray = new Object[capacity];
            System.arraycopy(array,0,newArray,0,size);
            array = newArray;
        }
    }

    //获取指定元素的值
    public Object get(int index){
        if (index>=0 && index < size){
            return array[index];
        }
        return new RuntimeException();
    }

    //删除指定索引的元素
    public Object remove(int index){
        Object result = array[index];
       if (index < size-1){
           System.arraycopy(array,index+1,array,index,size-index-1);
       }
        size--;
        return result;
    }

    //获取数组长度
    public int length(){
        return size;
    }

    //查询元素
    
    public void list(Consumer<Object> consumer){
        for (int i = 0; i < size; i++) {
            consumer.accept(array[i]);
        }
    }

    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    //iterator实现遍历,可以使用增强for循环调用
    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int i = 0;
            @Override
            public boolean hasNext() {
                return i < size;
            }

            @Override
            public E next() {
                return (E) array[i++];//先赋值后加1
            }
        };
    }


}
